<?php


namespace app\admin\controller\finance;


use app\common\controller\Adminbase;
use think\Db;

class Tongji extends Adminbase
{
    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit) = $this->buildTableParames();
            //获取列表
            $business_where[] = ['is_del', '=', 0];
            $filter = input('filter');
            if ($filter) {

                $filter = json_decode($filter, true);

                if (isset($filter['business_name'])) {
                    $business_where[] = ['business_name', 'like', '%' . $filter['business_name'] . '%'];
                }
                if (isset($filter['name'])) {
                    $business_where[] = ['name', 'like', '%' . $filter['name'] . '%'];
                }
                if (isset($filter['phone'])) {
                    $business_where[] = ['phone', 'like', '%' . $filter['phone'] . '%'];
                }
                if (isset($filter['c_address'])) {
                    $business_where[] = ['c_address', 'like', '%' . $filter['c_address'] . '%'];
                }
                if (isset($filter['province'])) {
                    $province = Db::name('area')->find($filter['province']);
                    $business_where[] = ['province', '=', $province['name']];
                }
                if (isset($filter['city'])) {
                    $city = Db::name('area')->find($filter['city']);
                    $business_where[] = ['city', '=', $city['name']];
                }

                if (isset($filter['create_time'])) {
                    $create_time = explode(' - ', $filter['create_time']);
                    foreach ($create_time as $k => $v) {
                        $create_time[$k] = strtotime($v);
                    }
                }
            }
            $_list = Db::name('business')
                ->where('status', 'in', [1, 2])    //0待审核 3审核失败
                ->page($page, $limit)
                ->where($business_where)
                ->order('create_time desc')
                ->select();

            foreach ($_list as $k => $v) {
                $_list[$k]['c_address'] = $v['province'] . $v['city'] . $v['area'] . $v['address'];
                //商家余额 商家订单数量 order_num  营业额 operate_amount  已提现金额  tixian_amount
                $order_where=array();
                $tixian_where=array();
                $order_where[] = ['is_del', '=', 0];
                $order_where[] = ['business_id', '=', $v['id']];
                $order_where[] = ['status', 'in', [3, 5, 6]];

                $tixian_where[] = ['type', '=', 2];
                $tixian_where[] = ['status', '=', 1];
                $tixian_where[] = ['business_id', '=', $v['id']];
                if ($create_time) {
                    $order_where[] = ['pay_time', 'between', [$create_time[0], $create_time[1]]];
                    $tixian_where[] = ['status_time', 'between', [$create_time[0], $create_time[1]]];
                }
                $_list[$k]['order_num2']=Db::name('order')->where($order_where)->count();
                $_list[$k]['operate_amount2']=Db::name('order')->where($order_where)->sum('price');
                $_list[$k]['tixian_amount2']=Db::name('business_finance')->where($tixian_where)->sum('money');

                $member_info = Db::name('member')->find($_list[$k]['member_id']);

                $_list[$k]['nickname'] = $member_info['nickname'];


                $_list[$k]['a']=$v['amount']>=$v['min_tixian']?number_format($v['amount']*(100-$v['commission'])/100,2):0;//可提现金额
                $_list[$k]['b']=$v['amount'];//未体现营业额
                $_list[$k]['c']=$v['business_volume'];//总营业额
                $_list[$k]['d']=Db::name('business_finance')->where([    //已提现总额
                    'business_id'=>$v['id'],
                    'type'=>2,
                    'status'=>1
                ])->sum('true_money');
            }
            //获取数量
            $total = Db::name('business')
                ->where('status', 'in', [1, 2])    //0待审核 3审核失败
                ->where($business_where)
                ->count();
            $result = ["code" => 0, "count" => $total, "data" => $_list];
            return json($result);
        }
        $area_list = Db::name('area')->where([
            ['id', '<>', 0],
            ['pid', '=', 0]
        ])->select();
        foreach ($area_list as $k => $v) {
            $proviec[$v['id']] = $v['name'];
        }
        $order_where2[] = ['is_del', '=', 0];
        $order_where2[]=['status', 'in', [2, 3, 5, 6]];

        $tixian_where2[] = ['type', '=', 2];
        $tixian_where2[] = ['status', '=', 1];

        $business_where[]=['is_del','=',0];

//        <li>平台总营业额：<span>{$data1}</span></li>
//        <li>商家可提现总额：<span>{$data2}</span></li>
//        <li>商家已提现总额：<span>{$data3}</span></li>
//        <li>商家未提现总额：<span>{$data4}</span></li>
//        <li>使用优惠券总额度：<span>{$data5}</span></li>


//        <li>平台总营业额：<span>{$data1}</span></li>
//        <li>商家提现到账总金额：<span>{$data2}</span></li>
//        <li>家已提现总营业额：<span>{$data4}</span></li>
//        <li>商家未提现总营业额：<span>{$data5}</span></li>
//        <li>使用优惠券总额度：<span>{$data6}</span></li>
//        <li>平台账户余额：<span>{$data7}</span></li>

        $data1=Db::name('order')->where($order_where2)->sum('price');

        $data2=Db::name('business_finance')->where($tixian_where2)->sum('true_money');

        $data3=Db::name('business_finance')->where($tixian_where2)->sum('money');

        $data4=Db::name('business')->whereColumn('amount', '>' ,'min_tixian')
            ->where($business_where)->sum('amount');

        $data5=Db::name('order')->where($order_where2)->sum('coupon_money');

        $data6=$data1-$data3-$data5;

//        $data2=Db::name('business')->whereColumn('amount', '>' ,'min_tixian')
//            ->where($business_where)->sum('amount');
//        $data3=Db::name('business_finance')->where($tixian_where2)->sum('true_money');
//        $data4=Db::name('business')->where($business_where)->sum('amount');
//        $data5=Db::name('order')->where($order_where2)->sum('coupon_money');

        $this->assign(['data1'=>$data1,'data2'=>$data2,'data3'=>$data3,'data4'=>$data4,'data5'=>$data5,'data6'=>$data6]);
        $this->assign('proviec', $proviec);
        return $this->fetch();
    }

    /**
     * 编辑
     * @return mixed|void
     * todo 图标url map_logo_url
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
//            if (count($data['row']['operate_cate']) > 3) {
//                $this->error('经营分类最多3种');
//            }
//            $data['row']['operate_cate'] = implode(",", $data['row']['operate_cate']);
            if ($data['row']['logo_url'] != $data['logo_url']) {
                $c1 = edit_img($data['row']['logo_url']);
                $c2 = c2($c1);
                $data['row']['logo_map'] = $c2;
            }
            $business_info = Db::name('business')
                ->where('is_del','=',0)
                ->where('id', $data['id'])
                ->update($data['row']);
            $this->success('操作成功');
        } else {
            $business_id = $this->request->param('id/d', 0);
            $data = Db::name('business') ->where('is_del','=',0)->where('id', $business_id)->find();
            $data['operate_cate'] = explode(',', $data['operate_cate']);
            //获取品牌
            $brand_list = Db::name('brand')
                ->where('is_del', 0)
                ->order('sort desc')
                ->select();
            //获取经营方式
            $operate_type_list = Db::name('operate_type')
                ->where('is_del', 0)
                ->order('sort desc')
                ->select();
            //获取经营类型
            $operate_cate = Db::name('operate_cate')
                ->where('is_del', 0)
                ->order('sort desc')
                ->select();
            $this->assign([
                'operate_cate' => $operate_cate,
                'operate_type_list' => $operate_type_list,
                'brand_list' => $brand_list,
                'data' => $data,
            ]);
            return $this->fetch();
        }
    }

    public function editStatus()
    {
        $business_id = $this->request->param('id/d', 0);
        $data = Db::name('business')->find($business_id);
        $status = $data['status'] == 2 ? 1 : 2;
        $update = array(
            'id' => $business_id,
            'status' => $status,
        );
        $result = Db::name('business')->update($update);
        if ($result) {
            return ['code' => 200, 'data' => '', 'msg' => '切换成功'];
        } else {
            return ['code' => 100, 'data' => '', 'msg' => '操作失败'];
        }
    }

    /**
     * 转移账号
     */
    public function change()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
//            $phone_result=validatePhoneNumber($data['phone']);
//            if (!$phone_result){
//                $this->error('输入合法手机号');
//            }
            $member_info = Db::name('member')->where('mobile', $data['phone'])->find();
            if (!$member_info) {
                $this->error('账户不存在');
            }
            $business_info = Db::name('business') ->where('is_del','=',0)->where('member_id', $member_info['id'])->find();
            if ($business_info) {
                $this->error('该账户已是商家');
            }
            $update_data = array(
                'id' => $data['id'],
                'member_id' => $member_info['id']
            );
            $result = Db::name('business')->update($update_data);
            if ($result) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $id = $this->request->param('id/d', 0);
            $this->assign("id", $id);
            return $this->fetch();
        }
    }

    /**
     * 查看
     */
    public function look()
    {
        $id = $this->request->param('id/d', 0);
        //近七天销售额
        //获取进七天时间戳范围
        //前几天 0代表当天的
        $timeScope = getTimestampScope(-7, 0);
        $order2where[] = ['pay_time', 'between', [$timeScope[0], $timeScope[1]]];
        $order1where[] = ['is_tui', '=', 0];
        $order1where[] = ['business_id', '=', $id];
        $day7_amount_count = Db::name('order')
            ->where($order1where)
            ->where($order2where)
            ->sum('price');
        //总销售额
        $amount_count = Db::name('order')
            ->where($order1where)
            ->sum('price');
        //订单总数量
        $order_count = Db::name('order')
            ->where($order1where)
            ->count();
        //提现金额
        $tixian_amount = Db::name('business_finance')
            ->where([
                'business_id' => $id,
                'type' => 2,
                'status' => 1
            ])
            ->sum('true_money');
        $this->assign([
            "business_id" => $id,
            "day7_amount_count" => $day7_amount_count,
            "amount_count" => $amount_count,
            "order_count" => $order_count,
            "tixian_amount" => $tixian_amount
        ]);
        return $this->fetch();
    }

    public function fdetail()
    {
        $param = $this->request->param();
        if ($this->request->isAjax()) {
            list($page, $limit) = $this->buildTableParames();

            $where[] = ['status', '=', 1];
            $where[] = ['type', '=', 2];
            $where[] = ['business_id', '=', $param['business_id']];
            $filter = input('filter');

            if ($filter) {
                $filter = json_decode($filter, true);
                if (isset($filter['id'])) {
                    $where[] = ['id', '=', $filter['id']];
                }
                if (isset($filter['status_time'])) {
                    $status_time = explode(' - ', $filter['status_time']);

                    foreach ($status_time as $k => $v) {
                        $status_time[$k] = strtotime($v);
                    }
                    $where[] = ['status_time', 'between', [$status_time[0], $status_time[1]]];
                }
                if (isset($filter['create_time'])) {
                    $create_time = explode(' - ', $filter['create_time']);
                    foreach ($create_time as $k => $v) {
                        $create_time[$k] = strtotime($v);
                    }
                    $where[] = ['create_time', 'between', [$create_time[0], $create_time[1]]];
                }
            }


            $_list = Db::name('business_finance')
                ->where($where)    //'提现状态 0未审核 1审核完成',
                ->page($page, $limit)
                ->order('status_time desc')
                ->select();
            foreach ($_list as $k => $v) {
                $_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $_list[$k]['status_time'] = date('Y-m-d H:i:s', $v['status_time']);
            }
            $total = Db::name('business_finance')
                ->where($where)    //'提现状态 0未审核 1审核完成',
                ->count();
            $result = ["code" => 0, "count" => $total, "data" => $_list];
            return json($result);
        }
        $this->assign([
            'business_id' => $param['business_id'],
            'status' => $param['status'],
        ]);
        return $this->fetch();
    }

    public function getc_cate()
    {
        $id = input('id');
        $query = db('area')->where('pid', $id)->select();
        return json(['code' => 200, 'data' => $query, 'msg' => '获取成功']);
    }

    public function del()
    {
        $param = $this->request->param();
        if ($this->request->isAjax()) {
            $update_data = array(
                'id' => $param['id'],
                'is_del' => 1
            );
            $result = Db::name('business')->update($update_data);
            if ($result) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }
        //获取商家信息
        $business_info = Db::name('business')->find($param['id']);
        //待核销订单
        $dai_count = Db::name('order')->where([
            'business_id' => $param['id'],
            'status' => 2,
            'is_del' => 0
        ])->count();
        //待回款订单 待回款订单金额
        $dai_huikuan = Db::name('order')->where([
            ['business_id', '=', $param['id']],
            ['is_to', '=', 0],
            ['status', 'in', [3, 5, 6]]
        ])->sum('price');
        $this->assign([
            'dai_count' => $dai_count,
            'dai_huikuan' => $dai_huikuan,
            'data' => $business_info,
        ]);
        return $this->fetch();
    }
}